<?php
require_once __DIR__ . '/../config/database.php';
require_once __DIR__ . '/Security.php';

class User {
    private $db;
    private $id;
    private $username;
    private $email;

    public function __construct() {
        $this->db = getDBConnection();
    }

    public function register($username, $email, $password) {
        try {
            // 检查用户名和邮箱是否已存在
            $stmt = $this->db->prepare("SELECT id FROM users WHERE username = ? OR email = ?");
            $stmt->execute([$username, $email]);
            if ($stmt->rowCount() > 0) {
                return ['success' => false, 'message' => '用户名或邮箱已存在'];
            }

            // 创建新用户
            $hashedPassword = Security::hashPassword($password);
            $stmt = $this->db->prepare("INSERT INTO users (username, email, password, created_at) VALUES (?, ?, ?, NOW())");
            $stmt->execute([$username, $email, $hashedPassword]);

            return ['success' => true, 'message' => '注册成功'];
        } catch (PDOException $e) {
            error_log("注册失败: " . $e->getMessage());
            return ['success' => false, 'message' => '注册失败，请稍后再试'];
        }
    }

    public function login($username, $password) {
        try {
            $stmt = $this->db->prepare("SELECT id, username, email, password FROM users WHERE username = ?");
            $stmt->execute([$username]);
            $user = $stmt->fetch();

            if ($user && Security::verifyPassword($password, $user['password'])) {
                // 更新最后登录时间
                $stmt = $this->db->prepare("UPDATE users SET last_login = NOW() WHERE id = ?");
                $stmt->execute([$user['id']]);

                // 设置会话
                $_SESSION['user_id'] = $user['id'];
                $_SESSION['username'] = $user['username'];
                $_SESSION['email'] = $user['email'];

                return ['success' => true, 'message' => '登录成功'];
            }

            return ['success' => false, 'message' => '用户名或密码错误'];
        } catch (PDOException $e) {
            error_log("登录失败: " . $e->getMessage());
            return ['success' => false, 'message' => '登录失败，请稍后再试'];
        }
    }

    public function logout() {
        session_destroy();
        return ['success' => true, 'message' => '已安全退出'];
    }

    public function isLoggedIn() {
        return isset($_SESSION['user_id']);
    }

    public function getCurrentUser() {
        if ($this->isLoggedIn()) {
            return [
                'id' => $_SESSION['user_id'],
                'username' => $_SESSION['username'],
                'email' => $_SESSION['email']
            ];
        }
        return null;
    }
}
?>